package com.leador.http;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.leador.core.Trace;
import com.leador.listener.OnPointListener;
import com.leador.listener.OnTrackListener;
import com.leador.module.ILocation;
import com.leador.module.SerEntity;
import com.leador.module.request.Entity;
import com.leador.module.request.Fence;
import com.leador.module.request.Historyalarm;
import com.leador.module.request.Track;
import com.leador.module.request.TrackRequest;
import com.leador.utils.Config;
import com.leador.utils.HttpTraceClientExchangeUtil;
import com.leador.utils.Utils;

import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by liuha on 2016/9/18.
 */
public class RequestParams {
    private static boolean isInit = false;
    private static String ak = "";
    private static String packCertPath = "";
    private static void init(Context paramContext) {
        if (isInit) {
            return;
        }
        if ("".equals(ak)) {
            ak = Trace.getKey(paramContext);
        }
        if ("".equals(packCertPath)) {
            packCertPath = Utils.getPackCertPath(paramContext);
        }
        isInit = true;
    }

    public static void getParams(String sName,String str, StringBuffer sb){
        if(str == null){
            return;
        }
        if (!TextUtils.isEmpty(str)) {
            try {
                sb.append("&"+sName).append("=").append(URLEncoder.encode(str, "UTF-8"));
            } catch (Exception localException) {
                sb.append("&"+sName).append("=").append(str);
            }
        }
    }

    /**
     * 1.新增服务ID
     * @param context
     * @param serEntity
     */
    public static void addServiceId(Context context, SerEntity serEntity,int ency) {
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        getParams("name", serEntity.getName(), sb);
        getParams("type", serEntity.getType(), sb);
        getParams("desc", serEntity.getDesc(), sb);
        //set property
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("service",ency,"service/add", "GET", 1, sb.toString());
        Request.request(context,httpClitenExchange);
    }

    public static void addEntity(Context context,Entity entity,int ency) {
        String str = getEntity(context,entity);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("entity",ency,"entity/add", "POST", 1, str);
        Request.request(context,httpClitenExchange);
    }

    public static void updateEntity(Context context,Entity entity,int ency) {
        String str = getEntity(context,entity);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("entity",ency,"entity/update", "POST", 2, str);
        Request.request(context,httpClitenExchange);
    }

    public static void deleteEntity(Context context,Entity entity,int ency){
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        getParams("service_id",String.valueOf(entity.getServiceId()),sb);
        getParams("entity_name",entity.getEntityName(),sb);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("entity",ency,"entity/delete", "POST", 3, sb.toString());
        Request.request(context,httpClitenExchange);
    }

    public static void listEntity(Context context,Entity entity,int ency){
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        getParams("service_id",String.valueOf(entity.getServiceId()),sb);
        getParams("entity_names",entity.getEntityName(),sb);
        //columnKey
        getColumnKey(entity.getColumnKey(),sb);
        getParams("active_time",entity.getActiveTime(),sb);
        getParams("return_type",entity.getReturnType(),sb);
        getParams("page_index",String.valueOf(entity.getPageIndex()),sb);
        getParams("page_size",String.valueOf(entity.getPageSize()),sb);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("entity",ency,"entity/list", "GET", 4, sb.toString());
        Request.request(context,httpClitenExchange);
    }

    public static void addcolumn(Context context,Entity entity,int ency){
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        getParams("service_id",String.valueOf(entity.getServiceId()),sb);
        getParams("column_key",entity.getColumnKey(),sb);
        getParams("column_desc",entity.getColumnDesc(),sb);
        getParams("is_search",entity.getIsSearch(),sb);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("entity",ency,"entity/addcolumn", "POST", 5, sb.toString());
        Request.request(context,httpClitenExchange);
    };

    public static void listcolumn(Context context,Entity entity,int ency){
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        getParams("service_id",String.valueOf(entity.getServiceId()),sb);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("entity",ency,"entity/listcolumn", "GET", 6, sb.toString());
        Request.request(context,httpClitenExchange);
    };

    public static void deletecolumn (Context context,Entity entity,int ency){
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        getParams("service_id",String.valueOf(entity.getServiceId()),sb);
        getParams("column_key",entity.getColumnKey(),sb);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("entity",ency,"entity/deletecolumn", "POST", 7, sb.toString());
        Request.request(context,httpClitenExchange);
    };

    /**
     * 新增轨迹 --> 比较特殊
     * @param context
     * @param iLocation
     * @param ency
     */
    public static void addTrack(Context context, ILocation iLocation,int ency){
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        sb.append("&service_id").append("=").append(iLocation.getService_id());
        sb.append("&entity_name").append("=").append(iLocation.getEntity_name());
        sb.append("&latitude").append("=").append(String.valueOf(iLocation.getLatitude()));
        sb.append("&longitude").append("=").append(String.valueOf(iLocation.getLongitude()));
        sb.append("&coord_type").append("=").append(iLocation.getCoord_type());
        long time = Long.valueOf(iLocation.getLoc_time());
        sb.append("&loc_time").append("=").append(String.valueOf(time));
        String custom = iLocation.getExtend1();
        if(custom != null && !custom.equals("")){
            String[] strArray = custom.split(";");
            for(String str : strArray){
                String[] single = str.split("-");
                sb.append("&"+single[0]).append("=").append(single[1]);
            }
        }
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("point",ency,"trace/addpoint", "POST", 2, sb.toString());
        Request.setRequest(context,httpClitenExchange);
    }

    public static void addTracks(Context context, int ency, String service_id, String entity_name, File file){
        init(context);
        StringBuffer sb = new StringBuffer();
        Map<String,String> argMaps = new HashMap<String, String>();
        argMaps.put("ak", ak);
        argMaps.put("service_id", service_id);
        argMaps.put("point_list", file.getName());
        argMaps.put("entity_name", entity_name);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("points",ency,"trace/addpoints", "POST", 3, sb.toString());
        Request.setFileRequest(context,file,argMaps,httpClitenExchange);
    }

    public static void gethistory(Context context, TrackRequest trackRequest,int ency){
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        getParams("service_id",String.valueOf(trackRequest.getService_id()),sb);
        getParams("entity_name",trackRequest.getEntity_name(),sb);
        getParams("start_time",trackRequest.getStart_time(),sb);
        getParams("end_time",trackRequest.getEnd_time(),sb);
        getParams("sort_type",String.valueOf(trackRequest.getSort_type()),sb);
        getParams("simple_return",String.valueOf(trackRequest.getSimple_return()),sb);
        getParams("is_processed",String.valueOf(trackRequest.getIs_processed()),sb);
        getParams("page_index",String.valueOf(trackRequest.getPage_index()),sb);
        getParams("page_size",String.valueOf(trackRequest.getPage_size()),sb);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("gethistory",ency,"trace/gethistory", "GET", 3, sb.toString());
        Request.request(context,httpClitenExchange);
    }

    public static void addcolumn(Context context,Track track,int ency){
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        getParams("service_id",String.valueOf(track.getServiceId()),sb);
        getParams("column_key",track.getColumnKey(),sb);
        getParams("column_desc",track.getColumnDesc(),sb);
        getParams("column_type",String.valueOf(track.getColumTyppe()),sb);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("track",ency,"trace/addcolumn", "POST", 4, sb.toString());
        Request.request(context,httpClitenExchange);
    }

    public static void listcolumn(Context context,Track track,int ency){
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        getParams("service_id",String.valueOf(track.getServiceId()),sb);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("track",ency,"trace/listcolumn", "GET", 5, sb.toString());
        Request.request(context,httpClitenExchange);
    }

    public static void deletecolumn(Context context,Track track,int ency){
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        getParams("service_id",String.valueOf(track.getServiceId()),sb);
        getParams("column_key",track.getColumnKey(),sb);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("track",ency,"trace/deletecolumn", "POST", 6, sb.toString());
        Request.request(context,httpClitenExchange);
    }

    public static void createFence(Context context, Fence fence,int ency){
        String str = getCreateFenceParams(context,fence);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("geofence",ency,"fence/create", "POST",fence.getShape(), str);//1代表圆形和2代表多边形。

        Request.request(context,httpClitenExchange);
    }

    public static void updateFence(Context context, Fence fence,int ency){
        String str = getUpdateFenceParams(context,fence);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("geofence",ency,"fence/update", "POST",3, str);//1代表圆形和2代表多边形。
        Request.request(context,httpClitenExchange);
    }

    public static void deleteFence(Context context,int serviceId,int fenceId,int ency){
        String str = getDeleteFenceParams(context,serviceId,fenceId);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("geofence",ency,"fence/delete", "POST",4, str);//1代表圆形和2代表多边形。
        Request.request(context,httpClitenExchange);
    }

    public static void getListFence(Context context, long serviceId, String fenceIds,String createIds,int ency) {
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        sb.append("&service_id").append("=").append(serviceId);
        if (!TextUtils.isEmpty(fenceIds)) {
            try {
                sb.append("&fence_ids").append("=").append(URLEncoder.encode(fenceIds, "UTF-8"));
            } catch (Exception localException) {
                sb.append("&fence_ids").append("=").append(fenceIds);
            }
        }

        if(!TextUtils.isEmpty(createIds)){
            try {
                sb.append("&creator").append("=").append(URLEncoder.encode(createIds, "UTF-8"));
            } catch (Exception localException) {
                sb.append("&creator").append("=").append(createIds);
            }
        }

        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("geofence",ency,"fence/list", "GET", 5, sb.toString());//1代表圆形和2代表多边形。
        Request.request(context,httpClitenExchange);
    }

    public static void queryMonitoredStatus(Context context,long serviceId,String monitoredPersons,int fenceId,int ency){
        String str = queryMonitoredStatusParams(context,serviceId,monitoredPersons,fenceId);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("geofence",ency,"fence/querystatus", "GET", 6, str);//1代表圆形和2代表多边形。
        Request.request(context,httpClitenExchange);
    }

    public static void queryFenceHistoryAlarmInfo(Context context, Historyalarm historyalarm,int ency){
        String str = getQueryFenceHistoryAlarmInfo(context,historyalarm);
        HttpTraceClientExchangeUtil httpClitenExchange
                = getHttpExchangeUtil("geofence",ency,"fence/historyalarm", "GET", 7, str);//1代表圆形和2代表多边形。
        Request.request(context,httpClitenExchange);
    }

    //-----------------------------------------------------------------------------
    public static HttpTraceClientExchangeUtil getHttpExchangeUtil(String discen,int ency,String endUrl,String requestType,int backFlag,String arg){
        HttpTraceClientExchangeUtil httpTraceClientExchangeUtil = new HttpTraceClientExchangeUtil();
        httpTraceClientExchangeUtil.setEncrypt(ency);
        httpTraceClientExchangeUtil.setDiscern(discen);
        String base_url = Config.BASE_URL + endUrl;
        httpTraceClientExchangeUtil.setUrl(base_url);
        httpTraceClientExchangeUtil.setRequstType(requestType);
        httpTraceClientExchangeUtil.setBackFlag(backFlag);
        httpTraceClientExchangeUtil.setArg(arg);
        return httpTraceClientExchangeUtil;
    }

    private static String getEntity(Context context, Entity entity) {
        init(context);
        StringBuffer sb = new StringBuffer();
        (sb = new StringBuffer()).append("ak=").append(ak);
        sb.append("&service_id").append("=").append(entity.getServiceId());
        if (!TextUtils.isEmpty(entity.getEntityName())) {
            try {
                sb.append("&entity_name").append("=").append(URLEncoder.encode(entity.getEntityName(), "UTF-8"));
            } catch (Exception localException) {
                sb.append("&entity_name").append("=").append(entity.getEntityName());
            }
        }
        if ((!TextUtils.isEmpty(entity.getColumnKey())) && (!Utils.checkArg(entity.getColumnKey(), "columnKey", sb))) {
            sb.append("&").append(entity.getColumnKey());
//            return "";
        }
        return sb.toString();
    }

    /**
     * 获取ColumnKey
     * @param columnKey
     * @param sb
     */
    public static void getColumnKey(String columnKey, StringBuffer sb){
        if(columnKey == null){
            return;
        }
        if ((!TextUtils.isEmpty(columnKey)) && (!Utils.checkArg(columnKey, "columnKey", sb))) {
            return;
        }
    }

    protected static String  getCreateFenceParams(Context context,Fence fence){
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        sb.append("&service_id").append("=").append(fence.getServiceId());
        sb.append("&name").append("=").append(fence.getFenceName());
        sb.append("&desc").append("=").append(fence.getFenceDesc());
        sb.append("&creator").append("=").append(fence.getCreator());
        sb.append("&monitored_persons").append("=").append(fence.getMonitoredPersons());
        sb.append("&valid_times").append("=").append(fence.getValidTimes());
        sb.append("&valid_cycle").append("=").append(fence.getValidCycle());
        sb.append("&valid_date").append("=").append(fence.getValidDate());
        sb.append("&valid_days").append("=").append(fence.getValidDays());
        sb.append("&shape").append("=").append(String.valueOf(fence.getShape()));
        sb.append("&coord_type").append("=").append(fence.getCoordType());
        sb.append("&center").append("=").append(fence.getCenter());
        sb.append("&radius").append("=").append(fence.getRadius());
        sb.append("&coordStr").append("=").append(fence.getCoordStr());
        sb.append("&alarm_condition").append("=").append(fence.getAlarmCondition());
        return sb.toString();
    }

    protected static String  getUpdateFenceParams(Context context,Fence fence){
        init(context);
        StringBuffer sb = new StringBuffer();
        sb.append("ak=").append(ak);
        sb.append("&service_id").append("=").append(fence.getServiceId());
        sb.append("&fence_id").append("=").append(fence.getFenceId());
        sb.append("&observers").append("=").append(fence.getObservers());
        sb.append("&name").append("=").append(fence.getFenceName());
        sb.append("&desc").append("=").append(fence.getFenceDesc());
        sb.append("&creator").append("=").append(fence.getCreator());
        sb.append("&monitored_persons").append("=").append(fence.getMonitoredPersons());
        sb.append("&valid_times").append("=").append(fence.getValidTimes());
        sb.append("&valid_cycle").append("=").append(fence.getValidCycle());
        sb.append("&valid_date").append("=").append(fence.getValidDate());
        sb.append("&valid_days").append("=").append(fence.getValidDays());
        sb.append("&shape").append("=").append(String.valueOf(fence.getShape()));
        sb.append("&coord_type").append("=").append(fence.getCoordType());
        sb.append("&center").append("=").append(fence.getCenter());
        sb.append("&radius").append("=").append(fence.getRadius());
        sb.append("&coordStr").append("=").append(fence.getCoordStr());
        sb.append("&alarm_condition").append("=").append(fence.getAlarmCondition());
        return sb.toString();
    }

    public static String getDeleteFenceParams(Context context,int serviceId,int fenceId){
        init(context);
        StringBuilder sb = new StringBuilder();
        sb.append("ak=").append(ak);
        sb.append("&service_id").append("=").append(String.valueOf(serviceId));
        sb.append("&fence_id").append("=").append(String.valueOf(fenceId));
        return sb.toString();
    }

    public static String queryMonitoredStatusParams(Context context,long serviceId,String monitoredPersons,int fenceId){
        init(context);
        StringBuilder sb = new StringBuilder();
        sb.append("ak=").append(ak);
        sb.append("&service_id").append("=").append(String.valueOf(serviceId));
        sb.append("&fence_id").append("=").append(String.valueOf(fenceId));
        sb.append("&monitored_persons").append("=").append(String.valueOf(monitoredPersons));
        return sb.toString();
    }
    public static String getQueryFenceHistoryAlarmInfo(Context context,Historyalarm historyalarm){
        init(context);
        StringBuilder sb = new StringBuilder();
        sb.append("ak=").append(ak);
        sb.append("&service_id").append("=").append(historyalarm.getServiceId());
        sb.append("&fence_id").append("=").append(historyalarm.getFenceId());
        if(!TextUtils.isEmpty(historyalarm.getMonitored_persons())) {
            try {
                sb.append("&monitored_persons").append("=").append(URLEncoder.encode(historyalarm.getMonitored_persons(), "UTF-8"));
            } catch (Exception var8) {
                sb.append("&monitored_persons").append("=").append(historyalarm.getMonitored_persons());
            }
        }

        if(historyalarm.getBeginTime() != 0) {
            sb.append("&begin_time").append("=").append(String.valueOf(historyalarm.getBeginTime()));
        }

        if(historyalarm.getEndTime() != 0) {
            sb.append("&end_time").append("=").append(historyalarm.getEndTime());
        }

        sb.append("&page_num").append("=").append(historyalarm.getPageNum());
        sb.append("&page_size").append("=").append(historyalarm.getPageSize());
        return sb.toString();
    }
}
